const Service = require('egg').Service

class UserService extends Service {
    async login(account, passwd) {
        const { app, ctx } = this
        const { mongo } = app

        let res = {}

        const user = await ctx.model.User.findOne({
            where: { account, passwd },
        })
        if (user) {
            // 账户和密码正确生成token
            const { account, name, id } = user
            const token = app.jwt.sign(
                {
                    exp: Math.floor(Date.now() / 1000) + 60 * 60,
                    data: {
                        account,
                        name,
                        id,
                    },
                },
                app.config.jwt.secret
            )
            res = {
                token,
                account,
                name,
                id,
            }

            // 把token存到mongodb
            mongo.User.findOneAndUpdate({ account }, { token: res.token }, (err, docs) => {
                if (!docs) {
                    const user_mongo = new mongo.User({
                        account,
                        token,
                    })
                    user_mongo.save()
                }
            })
        }

        return res
    }

    async getUserByAccount(account) {
        const user = await this.ctx.model.User.findOne({ where: { account } })
        return user
    }
}

module.exports = UserService
